<template>
  <div class="account_box">
    <div class="account_title">账户管理</div>

    <!-- 搜索区域 -->
    <div class="account_search">
      <div class="search_box">
        <el-input v-model="name_serch" class="name_search input" placeholder="请输入账户名称" :suffix-icon="Search" />
      </div>

      <div class="add_box">
        <el-button color="#0052CC" @click="openAddForm">新增</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table :data="paginatedData" style="width: 98%; margin-top: 2%; font-size: 13px" border>
        <el-table-column label="序号" width="60" align="center">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="账户名称" width="140" align="center">
          <template #default="data">
            {{ data.row.account }}
          </template>
        </el-table-column>
        <el-table-column label="账户头像" width="180" align="center">
          <template #default="scope">
            <el-image
              :src="getFullImageUrl(scope.row.imgs || scope.row.img)"
              style="width: 50px; height: 50px; border-radius: 50%"
              alt="用户头像"
              fit="cover"
              :preview-src-list="[getFullImageUrl(scope.row.imgs || scope.row.img)]"
              preview-teleported
              hide-on-click-modal
            />
          </template>
        </el-table-column>
        <el-table-column label="角色类型" width="180" align="center">
          <template #default="scope">
            <el-tag>{{ getRoleType(scope.row.roleid) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="角色名称" width="150" align="center">
          <template #default="scope">
            {{ getRoleName(scope.row.roleid) }}
          </template>
        </el-table-column>

        <el-table-column label="状态" width="150" align="center">
          <template #default="data">
            <el-switch v-model="data.row.status" inline-prompt active-text="开启" inactive-text="关闭" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="150" align="center">
          <template #default="scope">
            {{ scope.row.create_time }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        background
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑表单弹窗 -->
    <el-dialog v-model="dialogVisible" :title="type === 1 ? '新增账户' : '编辑账户'" width="700px">
      <el-form :model="form" label-width="100px" :rules="rules" ref="formRef" class="compact-form">
        <el-form-item label="账户名称" prop="account">
          <el-input v-model="form.account" placeholder="请输入账户名称" />
        </el-form-item>
        <el-form-item label="账户角色" prop="roleid">
          <el-select style="width: 100%" v-model="form.roleid" placeholder="请选择角色类型" @change="handleRoleChange">
            <el-option label="超级管理员" value="1" />
            <el-option label="劳务公司" value="2" />
            <el-option label="项目部" value="3" />
            <el-option label="薪资审核员" value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="账户密码" prop="password" :required="type === 1">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
          <template #help v-if="type === 2">
            <span class="text-xs text-gray-500">不修改密码请留空</span>
          </template>
        </el-form-item>

        <!-- 仅新增时显示确认密码 -->
        <el-form-item label="确认密码" prop="confirmPassword" v-if="type === 1">
          <el-input v-model="form.confirmPassword" type="password" placeholder="请再次输入密码" />
        </el-form-item>

        <!-- 劳务公司专属：管理费输入框 -->
        <el-form-item label="管理费" v-if="form.roleid === '2'">
          <div class="fee-input-group">
            <el-input v-model="form.manage_l" type="number" placeholder="长期" class="fee-input" min="0" step="0.01" precision="2" />
            <el-input v-model="form.manage_p" type="number" placeholder="短期" class="fee-input" min="0" step="0.01" precision="2" />
            <el-input v-model="form.manage_x" type="number" placeholder="学员" class="fee-input" min="0" step="0.01" precision="2" />
          </div>
        </el-form-item>

        <!-- 修改表单中的头像上传部分 -->
        <el-form-item label="头像" prop="img">
          <el-upload 
            class="avatar-uploader" 
            action="" 
            :show-file-list="false" 
            :http-request="handleCustomUpload" 
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.imgs || form.img" :src="getFullImageUrl(form.imgs || form.img)" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <!-- 添加预览按钮 -->
          <div v-if="form.imgs || form.img" class="avatar-preview mt-2">
            <el-button type="primary" link @click="previewAvatar">预览头像</el-button>
          </div>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" inline-prompt active-text="开启" inactive-text="关闭" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="头像预览" width="500px" append-to-body>
      <div class="text-center">
        <el-image
          :src="previewImageUrl"
          fit="contain"
          style="width: 100%; max-height: 70vh"
          :preview-src-list="[previewImageUrl]"
          :preview-teleported="true"
          hide-on-click-modal
        />
      </div>
      <template #footer>
        <el-button @click="previewVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { Search, Plus } from '@element-plus/icons-vue';
import { getRoleList } from '../../api/staff/index.js';
import { uploadImg, addaccount, delaccount } from '../../api/account/index.js';
import { ElMessage, ElMessageBox } from 'element-plus';

// 预览相关变量
const previewImageUrl = ref('')
const previewVisible = ref(false)

// 预览头像
const previewAvatar = () => {
  const imageUrl = getFullImageUrl(form.imgs || form.img);
  if (imageUrl) {
    previewImageUrl.value = imageUrl;
    previewVisible.value = true;
  }
}

// 表格数据
const data = ref([]);
const filteredData = ref([]); // 用于存储搜索过滤后的数据
const currentRow = ref(null);
let type = 1; // 1:新增 2:编辑

// 搜索相关
const name_serch = ref('');

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 计算分页后的数据
const paginatedData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  return filteredData.value.slice(startIndex, startIndex + pageSize.value);
});

// 监听搜索框变化，实现实时过滤
watch(name_serch, (newVal) => {
  filterData(newVal);
});

// 数据过滤函数
const filterData = (searchTerm) => {
  if (!searchTerm) {
    filteredData.value = [...data.value];
  } else {
    const term = searchTerm.toLowerCase();
    filteredData.value = data.value.filter((item) => item.account.toLowerCase().includes(term));
  }
  // 重置到第一页
  currentPage.value = 1;
  // 更新总条数
  total.value = filteredData.value.length;
};

// 分页事件处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 页码大小改变时重置到第一页
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 新增/编辑表单相关
const dialogVisible = ref(false);
const formRef = ref();
const form = reactive({
  account: '', // 账户名称
  img: '', // 头像相对路径
  imgs: '', // 头像完整路径
  password: '', // 密码
  confirmPassword: '', // 确认密码
  roleid: '', // 角色ID
  status: 1, // 状态 1:开启 0:关闭
  pid: 0, // 父ID，默认0
  type: 1, // 类型，默认1
  manage_l: 0, // 管理费长期
  manage_p: 0, // 管理费短期
  manage_x: 0, // 管理费学员
});

// 角色映射关系
const roleMap = {
  1: { type: '超级管理员', name: '超级管理员' },
  2: { type: '劳务公司', name: '劳务公司' },
  3: { type: '项目部', name: '项目部' },
  4: { type: '薪资审核员', name: '薪资审核员' },
};

// 获取角色类型
const getRoleType = (roleId) => {
  return roleMap[roleId]?.type || '未知角色';
};

// 获取角色名称
const getRoleName = (roleId) => {
  return roleMap[roleId]?.name || '未知角色';
};

// 角色变更处理
const handleRoleChange = () => {
  if (form.roleid !== '2') {
    form.manage_l = 0;
    form.manage_p = 0;
    form.manage_x = 0;
  }
};

// 表单验证规则
const rules = reactive({
  account: [
    { required: true, message: '请输入账户名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  img: [{ required: true, message: '请上传账户头像', trigger: 'change' }],
  roleid: [{ required: true, message: '请选择账户角色', trigger: 'change' }],
  password: [
    {
      required: (rule) => type === 1,
      message: '请输入账户密码',
      trigger: 'blur',
    },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
  ],
  confirmPassword: [
    {
      required: (rule) => type === 1 && form.password,
      message: '请确认密码',
      trigger: 'blur',
    },
    {
      validator: (rule, value, callback) => {
        if (form.password && value !== form.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  // 管理费验证规则
  manage_l: [
    { required: (rule) => form.roleid === '2', message: '请输入长期管理费', trigger: 'blur' },
    { type: 'number', min: 0, message: '管理费不能为负数', trigger: 'blur' },
  ],
  manage_p: [
    { required: (rule) => form.roleid === '2', message: '请输入短期管理费', trigger: 'blur' },
    { type: 'number', min: 0, message: '管理费不能为负数', trigger: 'blur' },
  ],
  manage_x: [
    { required: (rule) => form.roleid === '2', message: '请输入学员管理费', trigger: 'blur' },
    { type: 'number', min: 0, message: '管理费不能为负数', trigger: 'blur' },
  ],
});

// 生命周期
onMounted(() => {
  fetchData();
});

// 获取数据函数
const fetchData = () => {
  getRoleList()
    .then((res) => {
      data.value = res.data || [];
      filterData(''); // 初始化过滤数据
    })
    .catch((err) => {
      console.error('获取数据失败', err);
      ElMessage.error('获取数据失败');
    });
};

// 打开新增表单
const openAddForm = () => {
  resetForm();
  type = 1;
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    account: '',
    img: '',
    imgs: '',
    password: '',
    confirmPassword: '',
    roleid: '',
    status: 1,
    pid: 0,
    type: 1,
    manage_l: 0,
    manage_p: 0,
    manage_x: 0,
  });
  currentRow.value = null;
  if (formRef.value) {
    formRef.value.clearValidate();
  }
};

// 定义基础URL
const BASE_URL = 'http://labour_admin.kuxia.top';

// 获取完整图片URL的函数
const getFullImageUrl = (url) => {
  if (!url) return 'https://picsum.photos/200';

  // 如果已经是完整URL，直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }

  // 如果是相对路径，拼接基础URL
  if (url.startsWith('/')) {
    return BASE_URL + url;
  }

  // 其他情况添加基础URL和路径分隔符
  return `${BASE_URL}/${url}`;
};

// 自定义图片上传方法
const handleCustomUpload = async (options) => {
  try {
    // 创建FormData对象，用于传递文件
    const formData = new FormData();
    formData.append('file', options.file);

    // 调用导入的上传接口
    const response = await uploadImg(formData);

    // 假设接口返回格式为 { code: 1, data: { url: '图片路径' } }
    if (response?.data?.url) {
      form.img = response.data.url;
      form.imgs = response.data.url;
      options.onSuccess(response); // 通知上传成功
      ElMessage.success('头像上传成功');
    } else if (response?.url) {
      form.img = response.url;
      form.imgs = response.url;
      options.onSuccess(response); // 通知上传成功
      ElMessage.success('头像上传成功');
    } else {
      throw new Error(response?.msg || '上传失败');
    }
  } catch (error) {
    options.onError(error); // 通知上传失败
    ElMessage.error(error.message || '头像上传失败，请重试');
  }
};

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 准备提交数据
      const submitData = {
        ...JSON.parse(JSON.stringify(form)),
        roleid: Number(form.roleid),
        manage_l: Number(form.manage_l) || 0,
        manage_p: Number(form.manage_p) || 0,
        manage_x: Number(form.manage_x) || 0
      };
      
      // 移除确认密码字段
      delete submitData.confirmPassword;
      
      // 如果是编辑操作且密码为空，则不传递密码字段
      if (type === 2 && !form.password) {
        delete submitData.password;
      }

      addaccount(submitData)
        .then(res => {
          if (res.code === 1) {
            ElMessage.success(type === 1 ? '新增成功' : '修改成功');
            dialogVisible.value = false;
            // 重新获取数据
            fetchData();
          } else {
            ElMessage.error(res.msg || (type === 1 ? '新增失败' : '修改失败'));
          }
        })
        .catch(err => {
          console.error(type === 1 ? '新增失败' : '修改失败', err);
          ElMessage.error(err.message || (type === 1 ? '新增失败，请重试' : '修改失败，请重试'));
        });
    } else {
      return false;
    }
  });
};

// 编辑操作 - 优化角色回显
const handleEdit = (index, row) => {
  // 计算原始数据中的索引（因为index是分页后的索引）
  const originalIndex = data.value.findIndex((item) => item.id === row.id);
  if (originalIndex === -1) return;

  resetForm();
  type = 2;
  currentRow.value = data.value[originalIndex];

  // 填充表单数据，确保角色ID正确转换为字符串类型以匹配选项值
  Object.assign(form, {
    account: row.account,
    img: row.img,
    imgs: row.imgs,
    password: '', // 编辑时密码为空
    roleid: String(row.roleid), // 确保角色ID为字符串类型，与选项值类型一致
    status: row.status || 1,
    pid: row.pid || 0,
    type: row.type || 1,
    manage_l: row.manage_l || 0,
    manage_p: row.manage_p || 0,
    manage_x: row.manage_x || 0,
  });

  dialogVisible.value = true;
};

// 删除操作
const handleDelete = (index, row) => {
  // 计算原始数据中的索引
  const originalIndex = data.value.findIndex((item) => item.id === row.id);
  if (originalIndex === -1) return;

  ElMessageBox.confirm(`确定要删除 ${row.account} 吗?`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 调用删除接口
      delaccount({ id: row.id })
        .then(res => {
          if (res.code === 1) {
            ElMessage.success('删除成功');
            // 重新获取数据
            fetchData();
          } else {
            ElMessage.error(res.msg || '删除失败');
          }
        })
        .catch(err => {
          console.error('删除失败', err);
          ElMessage.error(err.message || '删除失败，请重试');
        });
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
};
</script>

<style scoped lang="scss">
.account_box {
  background-color: #fff;
  padding: 20px;
}

.account_title {
  background: #fff;
  width: 100%;
  height: 60px;
  font-size: 24px;
  font-weight: 500;
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.account_search {
  display: flex;
  justify-content: space-between;
  padding-left: 2%;
  padding-right: 2%;
  margin-bottom: 10px;
}

.name_search {
  width: 280px;
}

// 表格居中容器
.table-container {
  display: flex;
  justify-content: center;
}

// 分页容器样式
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  margin-bottom: 20px;
}

// 表格内容样式优化
:deep(.el-table td) {
  text-align: center;
  vertical-align: middle;
}

:deep(.el-table th) {
  text-align: center;
}

// 紧凑表单样式
.compact-form {
  :deep(.el-form-item) {
    margin-bottom: 12px; // 缩小表单控件间距
  }
}

// 头像上传样式
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

// 管理费输入框样式
.fee-input-group {
  display: flex;
  gap: 10px;
  width: 100%;

  .fee-input {
    flex: 1;
  }
}

// 预览按钮样式
.avatar-preview {
  margin-top: 10px;
}
</style>